//
//  UnifiedProfileView.swift
//  CMB250716
//
//  Created by Andy Lau on 29/7/25.
//

import SwiftUI
import LocalAuthentication

enum ProfileTab: String, CaseIterable {
    case personal = "personal"
}

struct UnifiedProfileView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    @State private var selectedTab: ProfileTab = .personal
    @State private var showingSaveSuccess = false
    @State private var editingName = false
    @State private var editingPhone = false
    @State private var editingEmail = false
    @State private var editingBirthday = false
    @State private var nameCompleted = false
    @State private var phoneCompleted = false
    @State private var emailCompleted = false
    @State private var birthdayCompleted = false
    @State private var showingPhoneVerification = false
    @State private var showingEmailVerification = false
    @State private var showingPhoneVerificationCode = false
    @State private var showingEmailVerificationCode = false
    @State private var verificationCode = ""
    @State private var phoneVerificationCode = ""
    @State private var emailVerificationCode = ""
    @State private var newPhoneNumber = ""
    @State private var newEmailAddress = ""
    @State private var tempName = ""
    @State private var tempPhone = ""
    @State private var tempEmail = ""
    @State private var tempBirthday = Date()
    @State private var selectedYear = 1990
    @State private var selectedMonth = 1
    @State private var correctPhoneVerificationCode = ""
    @State private var correctEmailVerificationCode = ""
    @State private var showingVerificationError = false
    @State private var verificationErrorMessage = ""

    
    // 计算属性：当前语言
    private var language: String {
        return dataManager.currentLanguage
    }
    
    // 计算完成度
    private var completionPercentage: Double {
        let completedCount = [nameCompleted, phoneCompleted, emailCompleted, birthdayCompleted].filter { $0 }.count
        return Double(completedCount) / 4.0 * 100
    }
    
    private var completedItems: Int {
        return [nameCompleted, phoneCompleted, emailCompleted, birthdayCompleted].filter { $0 }.count
    }
    
    private var totalItems: Int {
        return 4
    }
    
    // 手机验证sheet
    private var phoneVerificationSheet: some View {
        NavigationView {
            VStack(spacing: 24) {
                Text(language == "中文" ? "验证手机号" : "Verify Phone Number")
                    .font(.title2)
                    .fontWeight(.semibold)
                
                Text(language == "中文" ? "验证码已发送至 \(newPhoneNumber)" : "Verification code sent to \(newPhoneNumber)")
                    .font(.body)
                    .foregroundColor(.secondary)
                
                TextField(language == "中文" ? "请输入验证码" : "Enter verification code", text: $verificationCode)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .keyboardType(.numberPad)
                    .frame(maxWidth: 150)
                    .font(.system(size: 14))
                
                Button(language == "中文" ? "验证" : "Verify") {
                    if verificationCode == correctPhoneVerificationCode {
                        dataManager.currentUser?.phoneNumber = newPhoneNumber
                        showingPhoneVerification = false
                        editingPhone = false
                        phoneCompleted = true
                        verificationCode = ""
                        saveUserData()
                    } else {
                        verificationErrorMessage = language == "中文" ? "验证码错误，请重新输入" : "Incorrect verification code, please try again"
                        showingVerificationError = true
                        verificationCode = ""
                    }
                }
                .buttonStyle(.borderedProminent)
                .disabled(verificationCode.isEmpty)
                
                Spacer()
            }
            .padding()
            .navigationTitle(language == "中文" ? "验证手机" : "Verify Phone")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarItems(
                leading: Button(language == "中文" ? "取消" : "Cancel") {
                    showingPhoneVerification = false
                    editingPhone = false
                }
            )
        }
    }
    
    // 邮箱验证sheet
    private var emailVerificationSheet: some View {
        NavigationView {
            VStack(spacing: 24) {
                Text(language == "中文" ? "验证邮箱" : "Verify Email")
                    .font(.title2)
                    .fontWeight(.semibold)
                
                Text(language == "中文" ? "验证码已发送至 \(newEmailAddress)" : "Verification code sent to \(newEmailAddress)")
                    .font(.body)
                    .foregroundColor(.secondary)
                
                TextField(language == "中文" ? "请输入验证码" : "Enter verification code", text: $verificationCode)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .keyboardType(.numberPad)
                
                Button(language == "中文" ? "验证" : "Verify") {
                    if verificationCode == correctEmailVerificationCode {
                        dataManager.currentUser?.email = newEmailAddress
                        showingEmailVerification = false
                        editingEmail = false
                        emailCompleted = true
                        verificationCode = ""
                        saveUserData()
                    } else {
                        verificationErrorMessage = language == "中文" ? "验证码错误，请重新输入" : "Incorrect verification code, please try again"
                        showingVerificationError = true
                        verificationCode = ""
                    }
                }
                .buttonStyle(.borderedProminent)
                .disabled(verificationCode.isEmpty)
                
                Spacer()
            }
            .padding()
            .navigationTitle(language == "中文" ? "验证邮箱" : "Verify Email")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarItems(
                leading: Button(language == "中文" ? "取消" : "Cancel") {
                    showingEmailVerification = false
                    editingEmail = false
                }
            )
        }
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                // 深色渐变背景
                LinearGradient(
                    gradient: Gradient(stops: [
                        .init(color: Color(red: 0.05, green: 0.05, blue: 0.15), location: 0.0),
                        .init(color: Color(red: 0.1, green: 0.05, blue: 0.2), location: 0.3),
                        .init(color: Color(red: 0.15, green: 0.1, blue: 0.25), location: 0.6),
                        .init(color: Color(red: 0.08, green: 0.12, blue: 0.3), location: 1.0)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 20) {
                        personalInfoSection
                            
                            // 完成提示文字
                            if completionPercentage >= 100 {
                                Text("Profile Completed. Coupons Now Active.")
                                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                                    .foregroundColor(.green)
                                    .padding(.top, 9)
                                    .padding(.bottom, 30)
                            }
                        }
                        .padding()
                    }
            }
            .navigationBarHidden(true)
        }
        .onAppear {
            loadCompletionStatus()
        }
        .alert(language == "中文" ? "保存成功" : "Save Successful", isPresented: $showingSaveSuccess) {
            Button("OK") { }
        }
        .alert(verificationErrorMessage, isPresented: $showingVerificationError) {
            Button("OK") { }
        }
        .alert(dataManager.couponUnlockAlertMessage, isPresented: $dataManager.showingCouponUnlockAlert) {
            Button("OK") {
                dataManager.handleCouponUnlockAlertDismiss()
            }
        }
        .sheet(isPresented: $showingPhoneVerification) {
            phoneVerificationSheet
                .onAppear {
                    newPhoneNumber = tempPhone
                    correctPhoneVerificationCode = generateVerificationCode()
                }
        }
        .sheet(isPresented: $showingEmailVerification) {
            emailVerificationSheet
                .onAppear {
                    newEmailAddress = tempEmail
                    correctEmailVerificationCode = generateVerificationCode()
                }
        }
    }
    
    private func saveUserData() {
        dataManager.saveUser()
        saveCompletionStatus()
        
        // 检查是否完善了所有个人信息，如果是则激活member info completion礼券
        if dataManager.currentUser?.isMemberInfoComplete == true {
            dataManager.activateMemberInfoCompletionCoupon()
        }
    }
    
    private func saveCompletionStatus() {
        guard let phoneNumber = dataManager.currentUser?.phoneNumber else { return }
        let key = "\(AppConfig.StorageKeys.completionStatusPrefix)\(phoneNumber)"
        let status = [
            "nameCompleted": nameCompleted,
            "phoneCompleted": phoneCompleted,
            "emailCompleted": emailCompleted,
            "birthdayCompleted": birthdayCompleted
        ]
        UserDefaults.standard.set(status, forKey: key)
    }
    
    private func loadCompletionStatus() {
        guard let phoneNumber = dataManager.currentUser?.phoneNumber else { return }
        let key = "\(AppConfig.StorageKeys.completionStatusPrefix)\(phoneNumber)"
        if let status = UserDefaults.standard.dictionary(forKey: key) {
            nameCompleted = status["nameCompleted"] as? Bool ?? false
            phoneCompleted = status["phoneCompleted"] as? Bool ?? false
            emailCompleted = status["emailCompleted"] as? Bool ?? false
            birthdayCompleted = status["birthdayCompleted"] as? Bool ?? false
        }
        
        // 如果用户通过WhatsApp短信认证登录，手机号应该自动标记为已验证
        if dataManager.currentUser?.isPhoneVerified == true {
            phoneCompleted = true
            saveCompletionStatus() // 保存更新后的状态
        }
    }
    
    private func generateVerificationCode() -> String {
        // 测试阶段固定验证码为 123456
        return "123456"
        // 生产环境使用随机验证码：
        // return String(format: "%06d", Int.random(in: 100000...999999))
    }
    
    private var personalInfoSection: some View {
        VStack(spacing: 20) {
            // 标题行包含返回按钮和Personal Information
            HStack {
                Button(action: {
                    dismiss()
                }) {
                    Image(systemName: "chevron.left")
                        .font(.system(size: 18, weight: .semibold))
                        .foregroundColor(.white)
                        .frame(width: 32, height: 32)
                        .background(Color.white.opacity(0.1))
                        .clipShape(Circle())
                }
                
                Text(language == "中文" ? "个人信息" : "Personal Information")
                    .font(.system(size: 24, weight: .bold, design: .rounded))
                    .foregroundColor(.orange)
                
                Spacer()
            }
    
            
            personalInfoCard
            completionStatusCard
        }
        .padding(.top, 32)
    }
    
    private var personalInfoCard: some View {
        VStack(spacing: 0) {
            // Member ID行
            memberIDRow
            
            Divider()
                .background(Color.white.opacity(0.2))
                .padding(.leading, 64)
            
            // 姓名行
            nameEditRow
            
            Divider()
                .background(Color.white.opacity(0.2))
                .padding(.leading, 64)
            
            // 手机号行
            phoneEditRow
            
            Divider()
                .background(Color.white.opacity(0.2))
                .padding(.leading, 64)
            
            // 邮箱行
            emailEditRow
            
            Divider()
                .background(Color.white.opacity(0.2))
                .padding(.leading, 64)
            
            // 生日行
            birthdayEditRow
        }
        .background(
            RoundedRectangle(cornerRadius: 20)
                .fill(
                    LinearGradient(
                        gradient: Gradient(stops: [
                            .init(color: Color.white.opacity(0.15), location: 0.0),
                            .init(color: Color.white.opacity(0.08), location: 1.0)
                        ]),
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            LinearGradient(
                                gradient: Gradient(colors: [
                                    Color.white.opacity(0.3),
                                    Color.white.opacity(0.1)
                                ]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1
                        )
                )
                .shadow(color: .black.opacity(0.3), radius: 20, x: 0, y: 10)
        )
    }
    
    // Member ID显示行
    private var memberIDRow: some View {
        HStack(spacing: 20) {
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [Color.orange.opacity(0.3), Color.orange.opacity(0.1)]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 44, height: 44)
                
                Image(systemName: "creditcard.fill")
                    .font(.system(size: 20, weight: .semibold))
                    .foregroundColor(.orange)
            }
            
            VStack(alignment: .leading, spacing: 6) {
                HStack {
                    Text(language == "中文" ? "会员ID" : "Member ID")
                        .font(.system(size: 15, weight: .medium, design: .rounded))
                        .foregroundColor(.orange)
                    Spacer()
                }
                
                HStack {
                    Text(dataManager.currentUser?.memberID ?? "CMB-2507161688")
                        .font(.system(size: 17, weight: .semibold, design: .rounded))
                        .foregroundColor(.white)
                        .lineLimit(1)
                    Spacer()
                }
            }
            
            Spacer()
            
            // Member ID不可编辑，显示锁定图标
            Image(systemName: "lock.fill")
                .font(.system(size: 16, weight: .bold))
                .foregroundColor(.gray)
        }
        .padding(.horizontal, 24)
        .padding(.vertical, 20)
    }
    
    // 姓名编辑行
    private var nameEditRow: some View {
        HStack(spacing: 20) {
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [Color.blue.opacity(0.3), Color.blue.opacity(0.1)]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 44, height: 44)
                
                Image(systemName: "person.crop.circle.fill")
                    .font(.system(size: 20, weight: .semibold))
                    .foregroundColor(Color(red: 0.2, green: 0.4, blue: 1.0))
            }
            
            VStack(alignment: .leading, spacing: 6) {
                HStack {
                    Text(language == "中文" ? "姓名" : "Name")
                        .font(.system(size: 15, weight: .medium, design: .rounded))
                        .foregroundColor(.orange)
                    Spacer()
                }
                
                if editingName {
                    TextField(language == "中文" ? "输入姓名" : "Enter name", text: $tempName)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .onSubmit {
                            dataManager.currentUser?.name = tempName
                            editingName = false
                            nameCompleted = true
                            saveUserData()
                        }
                } else {
                    HStack {
                        Text(dataManager.currentUser?.name ?? (language == "中文" ? "未设置" : "Not Set"))
                            .font(.system(size: 17, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                            .lineLimit(1)
                        Spacer()
                    }
                }
            }
            
            Spacer()
            
            HStack(spacing: 12) {
                if nameCompleted {
                    Image(systemName: "checkmark.circle.fill")
                        .font(.system(size: 20, weight: .bold))
                        .foregroundColor(.green)
                }
                
                Button(action: {
                    if editingName {
                        dataManager.currentUser?.name = tempName
                        editingName = false
                        nameCompleted = true
                        saveUserData()
                    } else {
                        tempName = dataManager.currentUser?.name ?? ""
                        editingName = true
                    }
                }) {
                    ZStack {
                        Circle()
                            .fill(Color.white.opacity(0.1))
                            .frame(width: 20, height: 20)
                        
                        Image(systemName: editingName ? "checkmark" : "pencil")
                            .font(.system(size: 10, weight: .bold))
                            .foregroundColor(.orange)
                    }
                }
            }
        }
        .padding(.horizontal, 24)
        .padding(.vertical, 20)
    }
    
    // 手机号编辑行
    private var phoneEditRow: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color.green.opacity(0.3), Color.green.opacity(0.1)]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 44, height: 44)
                    
                    Image(systemName: "phone.circle.fill")
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(Color(red: 0.2, green: 0.8, blue: 0.4))
                }
                .padding(.leading, 24)
                
                Spacer(minLength: 20)
                
                VStack(alignment: .leading, spacing: 6) {
                    HStack {
                        Text(language == "中文" ? "手机号" : "Phone")
                            .font(.system(size: 15, weight: .medium, design: .rounded))
                            .foregroundColor(.orange)
                        Spacer()
                    }
                    
                    if editingPhone {
                        VStack(alignment: .leading, spacing: 4) {
                            TextField(language == "中文" ? "输入手机号" : "Enter phone", text: $tempPhone)
                                .textFieldStyle(RoundedBorderTextFieldStyle())
                                .keyboardType(.phonePad)
                            
                            Text(language == "中文" ? "请输入以8或9开头的8位数字" : "Please enter 8 digits starting with 8 or 9")
                                .font(.system(size: 12, weight: .regular))
                                .foregroundColor(.gray)
                        }
                    } else {
                        HStack {
                            Text(dataManager.currentUser?.phoneNumber ?? (language == "中文" ? "未设置" : "Not Set"))
                                .font(.system(size: 17, weight: .semibold, design: .rounded))
                                .foregroundColor(.white)
                                .lineLimit(1)
                            Spacer()
                        }
                    }
                }
                
                Spacer(minLength: 20)
                
                HStack(spacing: 12) {
                    if phoneCompleted {
                        Image(systemName: "checkmark.circle.fill")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(.green)
                    }
                    
                    Button(action: {
                        if editingPhone {
                            if showingPhoneVerificationCode {
                                // 验证码验证完成
                                dataManager.currentUser?.phoneNumber = tempPhone
                                editingPhone = false
                                showingPhoneVerificationCode = false
                                phoneCompleted = true
                                phoneVerificationCode = ""
                                saveUserData()
                            } else {
                                // 验证手机号格式
                                guard tempPhone.count == 8,
                                      tempPhone.allSatisfy({ $0.isNumber }),
                                      tempPhone.first == "8" || tempPhone.first == "9" else {
                                    verificationErrorMessage = language == "中文" ? "请输入正确的电话号码" : "Please enter a correct phone number"
                                    showingVerificationError = true
                                    return
                                }
                                
                                // 生成验证码并显示验证码输入
                                correctPhoneVerificationCode = generateVerificationCode()
                                showingPhoneVerificationCode = true
                            }
                        } else {
                            tempPhone = dataManager.currentUser?.phoneNumber ?? ""
                            editingPhone = true
                        }
                    }) {
                        ZStack {
                            Circle()
                                .fill(Color.white.opacity(0.1))
                                .frame(width: 20, height: 20)
                            
                            Image(systemName: editingPhone ? "checkmark" : "pencil")
                                .font(.system(size: 10, weight: .bold))
                                .foregroundColor(.orange)
                        }
                    }
                }
                .padding(.trailing, 24)
            }
            .padding(.vertical, 20)
            
            // 验证码输入栏
            if showingPhoneVerificationCode {
                HStack(spacing: 0) {
                    Spacer()
                        .frame(width: 44)
                        .padding(.leading, 24)
                    
                    Spacer(minLength: 20)
                    
                    VStack(alignment: .leading, spacing: 6) {
                        HStack {
                            Text(language == "中文" ? "验证码" : "Verification Code")
                                .font(.system(size: 15, weight: .medium, design: .rounded))
                                .foregroundColor(.orange)
                            Spacer()
                        }
                        
                        HStack {
                            TextField(language == "中文" ? "请输入验证码" : "Enter verification code", text: $phoneVerificationCode)
                                .textFieldStyle(RoundedBorderTextFieldStyle())
                                .keyboardType(.numberPad)
                                .font(.system(size: 14))
                                .frame(maxWidth: 170)
                            
                            Button(action: {
                                // 验证验证码
                                if phoneVerificationCode == correctPhoneVerificationCode {
                                    dataManager.currentUser?.phoneNumber = tempPhone
                                    editingPhone = false
                                    showingPhoneVerificationCode = false
                                    phoneCompleted = true
                                    phoneVerificationCode = ""
                                    saveUserData()
                                } else {
                                    verificationErrorMessage = language == "中文" ? "验证码错误，请重新输入" : "Incorrect verification code, please try again"
                                    showingVerificationError = true
                                    phoneVerificationCode = ""
                                }
                            }) {
                                ZStack {
                                    Circle()
                                        .fill(Color.green.opacity(0.2))
                                        .frame(width: 32, height: 32)
                                    
                                    Image(systemName: "checkmark")
                                        .font(.system(size: 12, weight: .bold))
                                        .foregroundColor(.green)
                                }
                            }
                            .disabled(phoneVerificationCode.isEmpty)
                        }
                    }
                    
                    Spacer(minLength: 20)
                }
                .padding(.bottom, 12)
            }
        }
    }
    
    // 邮箱编辑行
    private var emailEditRow: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color.orange.opacity(0.3), Color.orange.opacity(0.1)]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 44, height: 44)
                    
                    Image(systemName: "envelope.circle.fill")
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
                .padding(.leading, 24)
                
                Spacer(minLength: 20)
                
                VStack(alignment: .leading, spacing: 6) {
                    HStack {
                        Text(language == "中文" ? "邮箱" : "Email")
                            .font(.system(size: 15, weight: .medium, design: .rounded))
                            .foregroundColor(.orange)
                        Spacer()
                    }
                    
                    if editingEmail {
                        VStack(alignment: .leading, spacing: 4) {
                            TextField(language == "中文" ? "输入邮箱" : "Enter email", text: $tempEmail)
                                .textFieldStyle(RoundedBorderTextFieldStyle())
                                .keyboardType(.emailAddress)
                            
                            Text(language == "中文" ? "请输入有效的邮箱地址" : "Please enter a valid email address")
                                .font(.system(size: 12, weight: .regular))
                                .foregroundColor(.gray)
                        }
                    } else {
                        HStack {
                            Text(dataManager.currentUser?.email ?? (language == "中文" ? "未设置" : "Not Set"))
                                .font(.system(size: 17, weight: .semibold, design: .rounded))
                                .foregroundColor(.white)
                                .lineLimit(1)
                            Spacer()
                        }
                    }
                }
                
                Spacer(minLength: 20)
                
                HStack(spacing: 12) {
                    if emailCompleted {
                        Image(systemName: "checkmark.circle.fill")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(.green)
                    }
                    
                    Button(action: {
                        if editingEmail {
                            if showingEmailVerificationCode {
                                // 验证码验证完成
                                dataManager.currentUser?.email = tempEmail
                                editingEmail = false
                                showingEmailVerificationCode = false
                                emailCompleted = true
                                emailVerificationCode = ""
                                saveUserData()
                            } else {
                                // 验证邮箱格式
                                let emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
                                let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
                                guard emailPredicate.evaluate(with: tempEmail) else {
                                    verificationErrorMessage = language == "中文" ? "请输入有效的邮箱地址" : "Please enter a valid email address"
                                    showingVerificationError = true
                                    return
                                }
                                
                                // 生成验证码并显示验证码输入
                                correctEmailVerificationCode = generateVerificationCode()
                                showingEmailVerificationCode = true
                            }
                        } else {
                            tempEmail = dataManager.currentUser?.email ?? ""
                            editingEmail = true
                        }
                    }) {
                        ZStack {
                            Circle()
                                .fill(Color.white.opacity(0.1))
                                .frame(width: 20, height: 20)
                            
                            Image(systemName: editingEmail ? "checkmark" : "pencil")
                                .font(.system(size: 10, weight: .bold))
                                .foregroundColor(.orange)
                        }
                    }
                }
                .padding(.trailing, 24)
            }
            .padding(.vertical, 20)
            
            // 验证码输入栏
            if showingEmailVerificationCode {
                HStack(spacing: 0) {
                    Spacer()
                        .frame(width: 44)
                        .padding(.leading, 24)
                    
                    Spacer(minLength: 20)
                    
                    VStack(alignment: .leading, spacing: 6) {
                        HStack {
                            Text(language == "中文" ? "验证码" : "Verification Code")
                                .font(.system(size: 15, weight: .medium, design: .rounded))
                                .foregroundColor(.orange)
                            Spacer()
                        }
                        
                        HStack {
                            TextField(language == "中文" ? "请输入验证码" : "Enter verification code", text: $emailVerificationCode)
                                .textFieldStyle(RoundedBorderTextFieldStyle())
                                .keyboardType(.numberPad)
                                .font(.system(size: 14))
                                .frame(maxWidth: 170)
                            
                            Button(action: {
                                // 验证验证码
                                if emailVerificationCode == correctEmailVerificationCode {
                                    dataManager.currentUser?.email = tempEmail
                                    editingEmail = false
                                    showingEmailVerificationCode = false
                                    emailCompleted = true
                                    emailVerificationCode = ""
                                    saveUserData()
                                } else {
                                    verificationErrorMessage = language == "中文" ? "验证码错误，请重新输入" : "Incorrect verification code, please try again"
                                    showingVerificationError = true
                                    emailVerificationCode = ""
                                }
                            }) {
                                ZStack {
                                    Circle()
                                        .fill(Color.green.opacity(0.2))
                                        .frame(width: 32, height: 32)
                                    
                                    Image(systemName: "checkmark")
                                        .font(.system(size: 12, weight: .bold))
                                        .foregroundColor(.green)
                                }
                            }
                            .disabled(emailVerificationCode.isEmpty)
                        }
                    }
                    
                    Spacer(minLength: 20)
                }
                .padding(.bottom, 12)
            }
        }
    }
    
    // 生日编辑行
    private var birthdayEditRow: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color.purple.opacity(0.3), Color.purple.opacity(0.1)]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 44, height: 44)
                    
                    Image(systemName: "calendar.circle.fill")
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(Color(red: 0.8, green: 0.3, blue: 0.9))
                }
                .padding(.leading, 24)
                
                Spacer(minLength: 20)
                
                VStack(alignment: .leading, spacing: 6) {
                    HStack {
                        Text(language == "中文" ? "生日" : "Birthday")
                            .font(.system(size: 15, weight: .medium, design: .rounded))
                            .foregroundColor(.orange)
                        Spacer()
                    }
                    
                    HStack {
                        Text({
                            if let year = dataManager.currentUser?.birthYear,
                               let monthString = dataManager.currentUser?.birthMonth,
                               let month = Int(monthString) {
                                return "\(monthAbbreviation(for: month)) \(year)"
                            }
                            return language == "中文" ? "未设置" : "Not Set"
                        }())
                            .font(.system(size: 17, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                            .lineLimit(1)
                        Spacer()
                    }
                }
                
                Spacer(minLength: 20)
                
                HStack(spacing: 12) {
                    if birthdayCompleted {
                        Image(systemName: "checkmark.circle.fill")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(.green)
                    }
                    
                    Button(action: {
                        editingBirthday.toggle()
                        if editingBirthday {
                            if let yearString = dataManager.currentUser?.birthYear,
                               let monthString = dataManager.currentUser?.birthMonth,
                               let year = Int(yearString),
                               let month = Int(monthString) {
                                selectedYear = year
                                selectedMonth = month
                            }
                        } else {
                            dataManager.currentUser?.birthYear = String(selectedYear)
                            dataManager.currentUser?.birthMonth = String(format: "%02d", selectedMonth)
                            birthdayCompleted = true
                            saveUserData()
                        }
                    }) {
                        ZStack {
                            Circle()
                                .fill(Color.white.opacity(0.1))
                                .frame(width: 20, height: 20)
                            
                            Image(systemName: editingBirthday ? "checkmark" : "pencil")
                                .font(.system(size: 10, weight: .bold))
                                .foregroundColor(.orange)
                        }
                    }
                }
                .padding(.trailing, 24)
            }
            .padding(.vertical, 20)
            
            if editingBirthday {
                VStack(spacing: 12) {
                    Divider()
                        .background(Color.white.opacity(0.2))
                    
                    HStack {
                        Picker(language == "中文" ? "年" : "Year", selection: $selectedYear) {
                            ForEach(1950...2024, id: \.self) { year in
                                Text(String(year))
                                    .foregroundColor(.white)
                                    .tag(year)
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .frame(maxWidth: .infinity)
                        
                        Picker(language == "中文" ? "月" : "Month", selection: $selectedMonth) {
                            ForEach(1...12, id: \.self) { month in
                                Text(monthAbbreviation(for: month))
                                    .foregroundColor(.white)
                                    .tag(month)
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .frame(maxWidth: .infinity)
                    }
                    .frame(height: 120)
                    .padding(.horizontal, 24)
                    .padding(.bottom, 16)
                }
            }
        }
    }
    
    private func profileInfoRow(icon: String, iconColor: Color, title: String, value: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            HStack(spacing: 20) {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color.blue.opacity(0.2), Color.blue.opacity(0.1)]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 44, height: 44)
                    
                    Image(systemName: icon)
                        .font(.system(size: 20, weight: .semibold))
                        .foregroundColor(iconColor)
                }
                
                VStack(alignment: .leading, spacing: 6) {
                    Text(title)
                        .font(.system(size: 15, weight: .medium, design: .rounded))
                        .foregroundColor(.secondary)
                    
                    Text(value.isEmpty ? (language == "中文" ? "未设置" : "Not Set") : value)
                        .font(.system(size: 17, weight: .semibold, design: .rounded))
                        .foregroundColor(.primary)
                        .lineLimit(1)
                }
                
                Spacer()
                
                ZStack {
                    Circle()
                        .fill(Color.gray.opacity(0.1))
                        .frame(width: 32, height: 32)
                    
                    Image(systemName: "chevron.right")
                        .font(.system(size: 12, weight: .bold))
                        .foregroundColor(.secondary)
                }
            }
            .padding(.horizontal, 24)
            .padding(.vertical, 20)
        }
        .buttonStyle(PlainButtonStyle())
        .contentShape(Rectangle())
    }
    
    private var completionStatusCard: some View {
        VStack(spacing: 20) {
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text(language == "中文" ? "资料完成度" : "Profile Completion")
                        .font(.system(size: 20, weight: .bold, design: .rounded))
                        .foregroundColor(.white)
                    
                    Text(language == "中文" ? "完善资料获得更好体验" : "Complete your profile for better experience")
                        .font(.system(size: 14, weight: .medium, design: .rounded))
                        .foregroundColor(.white.opacity(0.7))
                }
                
                Spacer()
                
                // 环形进度条
                ZStack {
                    Circle()
                        .stroke(Color.white.opacity(0.3), lineWidth: 6)
                        .frame(width: 60, height: 60)
                    
                    Circle()
                        .trim(from: 0, to: CGFloat(completionPercentage) / 100)
                        .stroke(
                            LinearGradient(
                                gradient: Gradient(colors: [
                                    Color(red: 0.2, green: 0.4, blue: 1.0),
                                    Color(red: 0.4, green: 0.2, blue: 0.9)
                                ]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            style: StrokeStyle(lineWidth: 6, lineCap: .round)
                        )
                        .frame(width: 60, height: 60)
                        .rotationEffect(.degrees(-90))
                        .animation(.easeInOut(duration: 1.5), value: CGFloat(completionPercentage) / 100)
                    
                    Text("\(Int(completionPercentage))%")
                        .font(.system(size: 14, weight: .bold, design: .rounded))
                        .foregroundColor(.white)
                }
            }
            
            // 进度详情
            VStack(spacing: 12) {
                HStack {
                    Text(language == "中文" ? "已完成" : "Completed")
                        .font(.system(size: 15, weight: .medium, design: .rounded))
                        .foregroundColor(.white.opacity(0.7))
                    
                    Spacer()
                    
                    Text("\(completedItems)/\(totalItems) " + (language == "中文" ? "项" : "items"))
                        .font(.system(size: 15, weight: .semibold, design: .rounded))
                        .foregroundColor(.white)
                }
                
                ZStack(alignment: .leading) {
                    RoundedRectangle(cornerRadius: 6)
                        .fill(Color.white.opacity(0.3))
                        .frame(height: 8)
                    
                    RoundedRectangle(cornerRadius: 6)
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [
                                    Color(red: 0.2, green: 0.4, blue: 1.0),
                                    Color(red: 0.4, green: 0.2, blue: 0.9)
                                ]),
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .frame(width: UIScreen.main.bounds.width * 0.85 * (CGFloat(completedItems) / CGFloat(totalItems)), height: 8)
                        .animation(.easeInOut(duration: 1.2), value: CGFloat(completedItems) / CGFloat(totalItems))
                }
                
                HStack(spacing: 12) {
                    ForEach(0..<totalItems, id: \.self) { index in
                        Circle()
                            .fill(index < completedItems ? Color(red: 0.2, green: 0.4, blue: 1.0) : Color.white.opacity(0.3))
                            .frame(width: 8, height: 8)
                            .scaleEffect(index < completedItems ? 1.2 : 1.0)
                            .animation(.easeInOut(duration: 0.3).delay(Double(index) * 0.1), value: index < completedItems)
                    }
                    
                    Spacer()
                    
                    Text(language == "中文" ? "还差\(totalItems - completedItems)项" : "\(totalItems - completedItems) more to go")
                        .font(.system(size: 13, weight: .medium, design: .rounded))
                        .foregroundColor(.white.opacity(0.7))
                }
            }
        }
        .padding(24)
        .background(
            RoundedRectangle(cornerRadius: 20)
                .fill(
                    LinearGradient(
                        gradient: Gradient(stops: [
                            .init(color: Color.white.opacity(0.15), location: 0.0),
                            .init(color: Color.white.opacity(0.08), location: 1.0)
                        ]),
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            LinearGradient(
                                gradient: Gradient(colors: [
                                    Color.white.opacity(0.3),
                                    Color.white.opacity(0.1)
                                ]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1
                        )
                )
                .shadow(color: .black.opacity(0.3), radius: 20, x: 0, y: 10)
        )
    }
    
    private func monthAbbreviation(for month: Int) -> String {
        let monthNames = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
        return monthNames[month - 1]
    }

}

extension ProfileTab {
    func title(language: String) -> String {
        switch self {
        case .personal:
            return language == "中文" ? "个人信息" : "Personal"
        }
    }
}

#Preview {
    UnifiedProfileView()
        .environmentObject(DataManager.shared)
}